<template>
  <div class="manageTablePage">
    <div class="table" style="height: 90%">
      <!-- tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize) -->
      <el-table
        :border="true"
        style="width: 100%; height: 95%; margin-bottom: 15px"
        :data="tableData"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="serialNumber" label="序号" width="60">
          <template #default="scope">
            <div>
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userQuestion" label="用户问题" width="160" />

        <el-table-column prop="invalidType" label="响应类型" width="130">
          <template #default="scope">
            {{ getInvalidType(scope.row.resultType) }}
          </template>
        </el-table-column>

        <el-table-column prop="invalidResponse" label="响应结果" width="300">
          <template #default="scope">
            <p
              :style="{ 'overflow-y': 'auto', 'max-height': '200px', 'word-break': 'break-all'}"
              :innerHTML="
                getInvalidResponse(
                  scope.row.invalidResponse,
                  scope.row.resultType,
                  scope.row.resultData,
                  scope.row
                )
              "
            ></p>
          </template>
        </el-table-column>

        <el-table-column prop="userId" label="用户id" width="160">
          <template #default="scope">
            {{ scope.row.userId }}({{
              scope.row.userName ? scope.row.userName : "--"
            }})
          </template>
        </el-table-column>

        <el-table-column prop="role" label="所属角色" width="90">
          <template #default="scope">
            {{ ERole[scope.row.role] }}
          </template>
        </el-table-column>

        <el-table-column prop="version" label="学年阶段" width="100">
          <template #default="scope">
            {{ getVersionByArr(scope.row.version) }}
          </template>
        </el-table-column>

        <el-table-column prop="inputDevice" label="输入设备" width="100">
          <template #default="scope">
            {{ scope.row.inputDevice == "1" ? "PC端" : "移动端" }}
          </template>
        </el-table-column>

        <el-table-column prop="schoolId" label="所属学校" width="180">
          <template #default="scope">
            {{ (props.schoolMap.get(scope.row.schoolId) || scope.row.schoolName) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="gmtModified"
          label="提问时间"
          width="170"
          sortable
          :sort-method="sortTime"
        >
          <template #default="scope">
            {{ getNowTime(scope.row.gmtModified) }}
          </template>
        </el-table-column>

        <!-- <el-table-column prop="status" label="处理结果" width="90">
          <template #default="scope">
            <div v-if="getResultOfHandling(scope.row) === '已处理'">
              <span style="color: green; font-weight: 600">{{
                getResultOfHandling(scope.row)
              }}</span>
            </div>
            <div v-else>
              {{ getResultOfHandling(scope.row) }}
            </div>
          </template>
        </el-table-column> -->

        <el-table-column prop="remark" label="备注" width="200" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              @click="handleInstructs(scope.$index, scope.row)"
              :disabled="
                scope.row.isCheck === 1 || scope.row.invalidType == 1001
              "
              style="margin: 0 4px"
              >已处理</el-button
            >
            <el-button
              size="small"
              @click="editInstructs(scope.$index, scope.row)"
              style="margin: 0 4px"
              >再学习</el-button
            >
            <el-popconfirm
              title="确认要删除吗?"
              confirm-button-text="确认"
              cancel-button-text="取消"
              confirm-button-type="text"
              cancel-button-type="primary"
              @confirm="deleteInstructs(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger" style="margin: 0 4px"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-config-provider :locale="zhCn">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="props.totalSize || 0"
        >
        </el-pagination>
      </el-config-provider>
    </div>
  </div>
</template>
<script setup>
import { ElMessageBox } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { cloneDeep } from "lodash-es";
import { computed, ref } from "vue";
import { ERole } from "../enum";

const props = defineProps({
  tableData: Array,
  identityData: Array,
  editInstructs: Function,
  deleteInstructs: Function,
  remarkInstructs: Function,
  refresh: Function,
  changeInstructOpenType: Function,
  totalSize: Number,
  updatePageNum: Function,
  updatePageSize: Function,
  schoolMap: Object,
});

const currentPage = ref(1);
const pageSize = ref(10);
const totalSize = ref(0);

// 清除robotInstructNameAndSentenceDTOS长度为0的数据
const tableData = computed(() => {
  const arr = cloneDeep(props.tableData);

  for (let i = 0; i < arr?.length; i++) {
    let item = arr?.[i];
    let attribute = JSON.parse(item.attribute);
    const point = attribute?.point;
    const realMsgContent = attribute?.realMsgContent;

    item.userName = attribute?.userName;
    item.schoolName = attribute?.schoolName;
    item.role = attribute.role;
    item.version = attribute.version;
    item.remark = attribute?.remark || "";

    if (point > 0) {
      item.invalidType = "1001";
    } else if (point < 0) {
      item.invalidType = "2";
    } else {
      item.invalidType = attribute?.invalidType || "1";
    }

    if (realMsgContent && realMsgContent !== item.userQuestion) {
      item.userQuestion = realMsgContent + `(${item.userQuestion})`
    }

    item.invalidResponse = attribute?.resultData || attribute?.invalidResponse || "--";
    item.inputDevice = attribute?.inputDevice;
    item.resultType = attribute?.resultType || "";
    item.resultData = attribute?.resultData || "";
    item.modelFlag = attribute?.modelFlag || "";
  }

  totalSize.value = arr.length;

  return arr || [];
});

const tableRowClassName = (row, rowIndex) => {
  row = row.row;

  // 已解决/答案同意的记录
  if (row.isCheck === 1 || row.invalidType == 1001) {
    return "success-row";
  } else if (row.invalidType == 2) {
    return "warning-row";
  }
  return "";
};

const editInstructs = (index, row) => {
  props.editInstructs(index, row);
};

const deleteInstructs = (index, row) => {
  props.deleteInstructs(index, row);
};

const handleInstructs = (index, row) => {
  ElMessageBox.prompt("填写备注", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(({ value }) => {
      row.remark = value;
      props.remarkInstructs(index, row);
    })
    .catch(() => {});
};

const getVersionByArr = (version) => {
  if (!version) {
    return "--";
  }
  if (version.indexOf("1") != -1 && version.indexOf("2") != -1) {
    return "中小学、大学";
  } else if (version.indexOf("1") != -1) {
    return "大学";
  } else if (version.indexOf("2") != -1) {
    return "中小学";
  } else if (version.indexOf("4") !== -1) {
    return "中职";
  }
};

const getRoleByArr = (role) => {
  let str = "";
  for (let i = 0; i < role.length; i++) {
    str += ERole[role[i]];

    if (i != role.length - 1) {
      str += "、";
    }
  }
  return str;
};

const getInvalidResponse = (invalidResponse, resultType, resultData, item) => {
  const successFlag = "操作成功！",
    failedFlag = "操作失败。";

  if (invalidResponse == "--") {
    let resultStr = "";
    let resultArr = resultType?.split(",");

    //设备信息
    if (resultArr[0] == 3) {
      let operationType = resultArr?.[2] == 1 ? "打开设备" : "关闭设备";

      let operationResult = "";
      if (resultData.startsWith(successFlag)) {
        operationResult = successFlag;
        resultData = resultData.split(successFlag)[1];
      } else if (resultData.startsWith(failedFlag)) {
        operationResult = failedFlag;
        resultData = resultData.split(failedFlag)[1];
      } else {
        operationResult = "返回推荐列表";
      }

      resultStr = "<b>操作类型：</b>" + operationType + "<br>";
      resultStr += "<b>操作设备：</b>" + resultArr?.[1] + "<br>";
      resultStr += "<b>操作结果：</b>" + operationResult + "<br>";

      if (operationResult === "返回推荐列表") {
        resultStr += "<b>详情列表：</b><br>";
      } else {
        resultStr += "<b>设备详情：</b><br>";
      }

      let itemArr = resultData.split("|");
      itemArr.forEach((item) => {
        resultStr += item + "<br>";
      });
      console.log("resultStr=");
      return resultStr;
    }
  }

  resultType = Number(resultType.split(",")[0])

  let resultStr = "";
  switch (resultType) {
    case 1:
      resultStr = "<b>数据返回：</b><br>" + resultData
      break;
    case 2:
      let openArr = resultData.split(",");
      resultStr = `<b>打开指令</b><br>指令名称：${openArr[0]}<br>链接：${openArr[1]}`
      break;
    case 3:
      resultStr = "<b>控制操作</b><br>" + resultData
      break;
    case 5:
      resultStr = "<b>下载文件</b><br>" + resultData
      break;
    case 10:
      resultStr = "<b>服务</b><br>" + resultData
      break;
    case 99:
      let modelFlag = item?.modelFlag;
      let modelName = "大模型数据";
      switch (Number(modelFlag)) {
        case 1:
          modelName = "百度模型"
          break;
        case 2:
          modelName = "豆包大模型"
          break;
        case 3:
          modelName = "豆包智能体"
          break;
        case 4:
          modelName = "扣子智能体（测试）"
          break;
        case 5:
          modelName = "扣子智能体（商用）"
          break;
        default:
          break;
      }
      resultStr = `<b>${modelName}</b><br>` + resultData
      break;
    case 100:
      resultStr = "<b>指令列表</b><br>" + resultData
      break;
    case -1: {
      let modelFlag = item?.modelFlag;
      if (modelFlag === 4) {
        resultStr = "<b>扣子异常结果</b><br>" + resultData
      } else {
        resultStr = "<b>异常结果</b><br>" + resultData
      }
      break;
    }
    default:
      break;
  }

  return resultStr ? resultStr : invalidResponse;
};

const getInvalidType = (resultType) => {
  // if (invalidType == 1) {
  //   return "正常返回";
  // } else if (invalidType == 2) {
  //   return "答案未认同";
  // } else if (invalidType == 3) {
  //   return "系统未查询到相似指令";
  // } else if (invalidType == 4) {
  //   return "用户无权限查看";
  // } else if (invalidType == 1001) {
  //   return "答案认同";
  // }

  resultType = resultType?.split(",")?.[0]

  // 2024年11月27日14:48:37：使用resultType
  switch (Number(resultType)) {
    case 1: //数据返回
    case 2: //打开操作
    case 3: //设备控制
    case 4: //推荐指令
    case 5: //下载文件
    case 10: //服务
    case 99: //大模型数据
    case 100: //指令列表
      return "正常返回"
  }
  return "异常结果";
};

const getResultOfHandling = (row) => {
  if (row.invalidType == 1001) {
    return "---";
  }
  return row.isCheck === 1 ? "已处理" : "未处理";
};

const getNowTime = (time) => {
  let date = new Date(time);
  let Y = date.getFullYear() + "-";
  let M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  let D =
    date.getDate() < 10 ? "0" + date.getDate() + " " : date.getDate() + " ";
  let h =
    date.getHours() < 10 ? "0" + date.getHours() + ":" : date.getHours() + ":";
  let m =
    date.getMinutes() < 10
      ? "0" + date.getMinutes() + ":"
      : date.getMinutes() + ":";
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
};

const sortTime = (a, b) => {
  return getNowTime(b.gmtModified) - getNowTime(a.gmtModified);
};

const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  pageSize.value = val;
  currentPage.value = 1;

  props.updatePageSize(1, val);
};
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  currentPage.value = val;

  props.updatePageNum(val);
};
</script>

<style lang="scss" scoped>
.manageTablePage {
  height: 100%;
  overflow: auto;
  .centerItem {
    .centerItemTitle {
      margin-top: 30px;
    }
  }
}

:deep(.el-table) {
  --el-table-row-hover-bg-color: none !important;
  --el-table-border-color: #aaaaaa !important;
  --el-table-border: 1px solid #ebeef5 !important;

  thead th {
    font-size: 16px !important;
    color: #5c5454 !important;
    background-color: #d9d9d9;
  }

  thead {
    border: 1px solid #999999;
  }
}
</style>

<style>
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-7);
}
</style>
